package com.thinkcar.core.exception;

import com.thinkcar.core.enums.PublicExceptionEnum;
import com.thinkcar.core.exception.extension.CommonException;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.Objects;

/**
 * @author: jiangyong
 * @date: 2025/10/18
 * @description: GlobalExceptionHandler
 */
@ControllerAdvice
@Slf4j
@Hidden
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<PublicExceptionEnum> defaultArithmeticHandler(HttpServletRequest req, MethodArgumentNotValidException e) throws Exception {
        String msg = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error("请求url：{},参数校验失败:{}", req.getRequestURI(), msg);
        return Result.failed(PublicExceptionEnum.ARGUMENT_NOT_VALID.getCode(), e.getMessage());
    }

    /**
     * 处理自定义的业务异常
     *
     * @param e e
     * @return ResultResponse
     */
    @ExceptionHandler(value = CommonException.class)
    @ResponseBody
    public Result<PublicExceptionEnum> serviceExceptionHandler(CommonException e) {
        logger.error("发生业务异常！原因是：", e);
        return Result.failed(e.getErrorCode(), e.getErrorMessage());
    }

    /**
     * 处理空指针的异常
     *
     * @param e e
     * @return ResultResponse
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result<PublicExceptionEnum> exceptionHandler(NullPointerException e) {
        logger.error("发生空指针异常！原因是:", e);
        return Result.failed(PublicExceptionEnum.NULL_POINTER_EXCEPTION.getCode(), e.getMessage());
    }

    /**
     * 处理其他异常
     *
     * @param e e
     * @return ResultResponse
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<PublicExceptionEnum> exceptionHandler(Exception e) {
        // 检查是否为资源未找到异常
        if (e.getClass().getName().contains("NoResourceFoundException")) {
            if (e.getMessage().contains(".well-known")) {
                logger.debug("忽略.well-known路径的资源未找到异常: {}", e.getMessage());
                return Result.success();
            }
            logger.warn("静态资源未找到: {}", e.getMessage());
            return Result.failed(PublicExceptionEnum.RESOURCE_NOT_FOUND.getCode(), PublicExceptionEnum.RESOURCE_NOT_FOUND.getMsg());
        }
        logger.error("未知异常！原因是:", e);
        return Result.failed(PublicExceptionEnum.FAIL.getCode(), e.getMessage());
    }

}
